package com.ivncorp.evnproject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.ivncorp.evnproject.data.CotDao;
import com.ivncorp.evnproject.data.DaoMaster;
import com.ivncorp.evnproject.data.DaoMaster.DevOpenHelper;
import com.ivncorp.evnproject.data.DaoSession;
import com.ivncorp.evnproject.helpers.ExifHelpers;
import com.ivncorp.evnproject.helpers.LocationTracker;
import com.ivncorp.evnproject.helpers.SetupPhotos;
import com.ivncorp.evnproject.helpers.Utils;
import com.ivncorp.evnproject.helpers.Variables;
import com.ivncorp.evnproject.model.InputCot;
import com.ivncorp.evnproject.model.ObjectCot;

public class ActivityCreateCot extends Activity {

	private LocationTracker locationTracker;
	// private GPSTracker gpsTracker;
	private static final int CAMERA_REQUEST_1 = 1;
	private static final int CAMERA_REQUEST_2 = 2;
	private static final int CAMERA_REQUEST_3 = 3;

	private Boolean Creat = true;

	private ObjectCot object;

	private String mCurrentPhotoPath = "";
	private HashMap<String, String> list_mCurrentPhotoPath;
	private SetupPhotos setupphotos;
	private ImageView iv1;
	private ImageView iv2;
	private ImageView iv3;
	private EditText txtCode;
	private EditText txtName;
	private Bitmap bitmap = null;
	// for DAO
	private SQLiteDatabase dbDao;
	private DaoSession daoSession;
	private DaoMaster daoMaster;
	private CotDao cotDao;

	private ArrayList<InputCot> listInput = new ArrayList<InputCot>();

	@SuppressLint("SimpleDateFormat")
	SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm:ss.SSS");

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_cot);

		iv1 = (ImageView) findViewById(R.id.ivCreateCot1);
		iv2 = (ImageView) findViewById(R.id.ivCreateCot2);
		iv3 = (ImageView) findViewById(R.id.ivCreateCot3);
		txtCode = (EditText) findViewById(R.id.txtCreateCotCode);
		txtName = (EditText) findViewById(R.id.txtCreateCotName);

		// set data
		loadData();
		// String[] namesArr = new String[listInput.size()];
		// for (int i = 0; i < listInput.size(); i++) {
		// namesArr[i] = listInput.get(i).getName();
		// }
		// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
		// android.R.layout.simple_spinner_item, namesArr);
		// spName.setAdapter(adapter);
		// spName.setOnItemSelectedListener(new OnItemSelectedListener() {
		//
		// @Override
		// public void onItemSelected(AdapterView<?> parent, View view,
		// int position, long id) {
		// txtCode.setText(listInput.get(position).getCode());
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> parent) {
		// // TODO Auto-generated method stub
		//
		// }
		// });

		locationTracker = new LocationTracker(this);
		// gpsTracker = new GPSTracker(this);
		list_mCurrentPhotoPath = new HashMap<String, String>();
		setupphotos = new SetupPhotos();

		// Dao
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(
				getApplicationContext(), Variables.NAME_DATABSE, null);
		dbDao = helper.getWritableDatabase();
		daoMaster = new DaoMaster(dbDao);
		daoSession = daoMaster.newSession();
		cotDao = daoSession.getCotDao();

		Intent intent = getIntent();
		object = (ObjectCot) intent.getSerializableExtra("object");
		if (object != null) {

			txtCode.setText(object.getCode());
			txtName.setText(object.getName());

			final int width = iv1.getLayoutParams().width;
			final int height = iv1.getLayoutParams().height;

			String uri1 = object.getImage_1();
			if (uri1 != null) {
				bitmap = Utils.decodeFile(uri1, width, height);
				iv1.setImageBitmap(bitmap);
			}
			String uri2 = object.getImage_2();
			if (uri2 != null) {
				bitmap = Utils.decodeFile(uri2, width, height);
				iv2.setImageBitmap(bitmap);
			}

			String uri3 = object.getImage_3();
			if (uri3 != null) {
				bitmap = Utils.decodeFile(uri3, width, height);
				iv3.setImageBitmap(bitmap);
			}

			Creat = false;
		}
		getActionBar().setDisplayShowHomeEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		if (bitmap != null) {
			bitmap.recycle();
			bitmap = null;
		}
		iv1.setImageBitmap(null);
		iv2.setImageBitmap(null);
		iv3.setImageBitmap(null);
		super.onDestroy();
	}

	public void imageclick(View view) {
		switch (view.getId()) {
		case R.id.layoutCreateCot1:
			Toast.makeText(this, R.string.hinh_dang, Toast.LENGTH_LONG).show();
			dispatchTakePictureIntent(true, CAMERA_REQUEST_1);
			break;
		case R.id.layoutCreateCot2:
			Toast.makeText(this, R.string.hinh_dang_1, Toast.LENGTH_LONG)
					.show();
			dispatchTakePictureIntent(false, CAMERA_REQUEST_2);
			break;
		case R.id.layoutCreateCot3:
			Toast.makeText(this, R.string.hinh_dang_2, Toast.LENGTH_LONG)
					.show();
			dispatchTakePictureIntent(false, CAMERA_REQUEST_3);
			break;
		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode == Activity.RESULT_OK) {
			if (mCurrentPhotoPath != null) {
				switch (requestCode) {
				case CAMERA_REQUEST_1:
					new ExifHelpers().setExifGPS(mCurrentPhotoPath,
							getApplicationContext());
					bitmap = Utils.decodeFile(mCurrentPhotoPath,
							iv1.getWidth(), iv1.getHeight());
					iv1.setImageBitmap(bitmap);
					list_mCurrentPhotoPath.put("1", mCurrentPhotoPath);
					break;
				case CAMERA_REQUEST_2:
					bitmap = Utils.decodeFile(mCurrentPhotoPath,
							iv2.getWidth(), iv2.getHeight());
					iv2.setImageBitmap(bitmap);
					list_mCurrentPhotoPath.put("2", mCurrentPhotoPath);
					break;
				case CAMERA_REQUEST_3:
					bitmap = Utils.decodeFile(mCurrentPhotoPath,
							iv3.getWidth(), iv3.getHeight());
					iv3.setImageBitmap(bitmap);
					list_mCurrentPhotoPath.put("3", mCurrentPhotoPath);
					break;
				default:
					break;
				}

				mCurrentPhotoPath = null;
			}

		} else {
			new File(mCurrentPhotoPath).delete();
		}

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_takepicture_action, menu);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.action_takepicture:
			savedata();
			break;

		case android.R.id.home:
			finish();
			break;

		default:
			break;
		}

		return super.onOptionsItemSelected(item);
	}

	public void savedata() {

		String code = txtCode.getText().toString();
		String name = txtName.getText().toString();

		if (code.isEmpty()) {
			Toast.makeText(getApplicationContext(),
					R.string.yeu_cau_nhap_vao_ma_cot_, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		if (name.isEmpty()) {
			Toast.makeText(getApplicationContext(),
					R.string.yeu_cau_nhap_vao_ten_cot_, Toast.LENGTH_SHORT)
					.show();
			return;
		}
		ObjectCot ob = new ObjectCot();
		if (list_mCurrentPhotoPath.get("1") == null) {
			if (Creat) {
				Toast.makeText(getApplicationContext(),
						R.string.yeu_cau_anh_hinh_dang_, Toast.LENGTH_SHORT)
						.show();
				return;
			} else
				ob.setImage_1(object.getImage_1());
		} else {
			ob.setImage_1(list_mCurrentPhotoPath.get("1"));
		}
		if (list_mCurrentPhotoPath.get("2") == null) {
			if (Creat) {
				Toast.makeText(getApplicationContext(),
						R.string.yeu_cau_anh_toan_dien_, Toast.LENGTH_SHORT)
						.show();
				return;
			} else
				ob.setImage_2(object.getImage_2());
		} else {
			ob.setImage_2(list_mCurrentPhotoPath.get("2"));
		}
		if (list_mCurrentPhotoPath.get("3") == null) {
			if (Creat) {
				Toast.makeText(getApplicationContext(),
						R.string.yeu_cau_anh_chi_tiet_, Toast.LENGTH_SHORT)
						.show();
				return;
			} else
				ob.setImage_3(object.getImage_3());
		} else {
			ob.setImage_3(list_mCurrentPhotoPath.get("3"));
		}
		ob.setUploaded((byte) 0);
		ob.setCode(code);
		ob.setName(name);
		Calendar calendar = Calendar.getInstance();
		Date date = new Date(calendar.getTimeInMillis());
		ob.setTimestamp(dateFormat.format(date));

		// test
		// ob.setImage_3("/mnt/sdcard/DCIM/Camera/bieu do luong du lieu muc dinh.jpg");
		// ob.setImage_2("/mnt/sdcard/DCIM/Camera/bieu do luong du lieu muc dinh.jpg");
		// ob.setImage_1("/mnt/sdcard/DCIM/Camera/bieu do luong du lieu muc dinh.jpg");

		if (Creat) {
			if (cotDao.insert(ob) > -1) {
				Toast.makeText(getApplicationContext(),
						R.string.tao_thanh_cong_, Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), R.string.tao_that_bai_,
						Toast.LENGTH_SHORT).show();
			}
		} else {
			try {
				ob.setId_object(object.getId_object());
				cotDao.update(ob);
				Toast.makeText(getApplicationContext(),
						R.string.chinh_sua_thanh_cong_, Toast.LENGTH_SHORT)
						.show();

			} catch (Exception e) {
				Toast.makeText(getApplicationContext(),
						R.string.chinh_sua_khong_thanh_cong_,
						Toast.LENGTH_SHORT).show();
			}
		}

		finish();

	}

	private void dispatchTakePictureIntent(boolean gps, int request) {

		Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		File filephoto = null;
		try {
			filephoto = setupphotos.createImageFile();

		} catch (IOException e) {
			e.printStackTrace();
			filephoto = null;
			mCurrentPhotoPath = null;
		}
		if (gps) {
			if (!locationTracker.servicesConnected()) {
				Toast.makeText(this,
						R.string.kiem_tra_ket_noi_internet_hoac_bat_gps,
						Toast.LENGTH_SHORT).show();
				return;
			}
		}
		if (filephoto != null) {
			takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(filephoto));
			mCurrentPhotoPath = filephoto.getAbsolutePath();
			startActivityForResult(takePictureIntent, request);

		}

	}

	// get data
	AssetManager manager;

	private String readDataAsset() {
		String line;
		StringBuilder builder = new StringBuilder();
		manager = this.getAssets();
		try {
			InputStream is = manager.open("api.txt");
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			while ((line = br.readLine()) != null) {
				builder.append(line);
				builder.append("\n");
			}
			br.close();
		} catch (Exception e) {

		}
		return builder.toString();
	}

	private void loadData() {
		try {
			JSONObject jsonObject = new JSONObject(readDataAsset());
			JSONArray array = jsonObject.getJSONArray("tram");
			for (int i = 0; i < array.length(); i++) {
				JSONObject object = array.getJSONObject(i);
				listInput.add(new InputCot(object.getString("ma"), object
						.getString("ten")));
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
